<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--供应商商品-->
			<view class="detail-item">
				<view class="main-flex">
					<uni-section title="供应商商品" type="line"></uni-section>
					<!--操作-->
					<view class="operate main-flex">
						<up-button
							class="operate-btn main-flex"
							size="mini"
							type="primary"
							@click="loopFun(info?.productId || '')">
							<uni-icons class="operate-btn-icon" type="loop" size="28rpx" color="#ffffff"></uni-icons>
							<view class="operate-btn-text">更新商品信息</view>
						</up-button>
					</view>
				</view>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
						<uni-forms-item label="供应商" name="supplierId" required>
							<ty-data-select
								v-model="formData.supplierId"
								placeholder="请选择供应商"
								dataKey="name"
								dataValue="id"
								filterable
								:disabled="!!id"
								@change="changeSupplier"
								:localdata="supplierList">
							</ty-data-select>
					  </uni-forms-item>
						<uni-forms-item label="商品名称" name="productName" required>
						  <uni-easyinput :disabled="!!id" v-model="formData.productName" placeholder="请选择商品" />
							<view class="select-readonly" @click="openProduct"></view>
						</uni-forms-item>
						<uni-forms-item label="区域" name="regionCode" required>
							<uni-data-select
								v-model="formData.regionCode"
								placeholder="请选择区域"
								:disabled="!!id"
								:localdata="setStore.allProvinceList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品类型" name="typeName" required>
						  <ty-data-select
						  	v-model="formData.typeName"
						  	placeholder="请选择商品类型"
						  	filterable
								:disabled="!!id"
						  	:localdata="productTypeList">
						  </ty-data-select>
						</uni-forms-item>
						<uni-forms-item label="单位" name="unit" required>
						  <ty-data-select
						  	v-model="formData.unit"
						  	placeholder="请选择单位"
						  	filterable
								:disabled="!!id"
						  	:localdata="zyzProductUnitList">
						  </ty-data-select>
						</uni-forms-item>
						<uni-forms-item label="采购价格" name="purchasePrice" required>
						  <uni-easyinput type="number" v-model="formData.purchasePrice" placeholder="请输入采购价格" />
						</uni-forms-item>
						<uni-forms-item style="display: none;" label="规格" name="moreSpec">
						  <uni-easyinput v-model="formData.moreSpec" placeholder="请输入规格" />
						</uni-forms-item>
						<uni-forms-item style="display: none;" label="商品ID" name="productId">
						  <uni-easyinput v-model="formData.productId" placeholder="请输入商品ID" />
						</uni-forms-item>
						<uni-forms-item label="备注" name="remark">
							<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入备注"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
		<ty-product-picker
			@close="closeProduct"
			@change="changeProduct"
			:showProduct="showProduct"></ty-product-picker>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch, nextTick } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { supplierProductDetail, editSupplierProduct } from "@/api/erp_api/purchase"
import { systemDictStatusList } from '@/utils/config.js'
import { allSupplier } from "@/api/erp_api/purchase"
import { zyzProductUnit } from "@/api/system/dict/data"
import { productType, productDetail } from "@/api/erp_api/product"

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad(async (option) => {
		getProductType()
		getAllSupplier()
		getZyzProductUnit()
		if (option.id) {
			uni.setNavigationBarTitle({
				title: '修改供应商商品'
			})
			id.value = option.id
			getDetail()
		}
	})
	
	// 获取商品类别
	const productTypeList = ref([])
	const getProductType = () => {
		return productType().then(res => {
			productTypeList.value = res.rows.map(item => {
				return {
					...item,
					value: `${item.name}`,
					text: `${item.name}`
				}
			}).filter(item => item.parentId) || []
		})
	}
	
	// 商品单位
	const zyzProductUnitList = ref([])
	const getZyzProductUnit = () => {
		return zyzProductUnit().then(res => {
			zyzProductUnitList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictLabel,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 获取供应商
	const supplierList = ref()
	const getAllSupplier = () => {
		allSupplier().then(res => {
			supplierList.value = res.data.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	const changeSupplier = (e) => {
		console.log(e)
	}
	
	// 商品选择
	const showProduct = ref(false)
	const openProduct = () => {
		if (!id.value) {
			showProduct.value = true
		}
	}
	const closeProduct = () => {
		showProduct.value = false
	}
	const changeProduct = (e) => {
		if (e.length > 0) {
			formData.value.moreSpec = e[0].moreSpec
			formData.value.regionCode = e[0].regionCode
			formData.value.purchasePrice = e[0].purchasePrice
			formData.value.productId = e[0].id
			formData.value.productName = e[0].name
			formData.value.typeName = e[0].typeName
			formData.value.unit = e[0].unit
			formData.value.regionCode = e[0].regionCode
		}
	}
	
	// 获取商品信息
	const productInfo = ref({})
	const getProductDetail = (id) => {
		productDetail({
			id
		}).then(res => {
			if (res?.data) {
				productInfo.value = res.data
			}
		})
	}
	
	// 更新商品信息
	const loopFun = () => {
		if (productInfo.value?.id) {
			formData.value = {
				moreSpec: productInfo.value.moreSpec,
				productId: info.value.productId,
				productName: productInfo.value.name,
				purchasePrice: productInfo.value.purchasePrice,
				regionCode: productInfo.value.regionCode,
				supplierId: info.value.supplierId,
				typeName: productInfo.value.typeName,
				unit: productInfo.value.unit
			}
		}
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		supplierProductDetail({
			id: id.value
		}).then(res => {
			info.value = res.data || {}
			formData.value = {
				moreSpec: res.data.moreSpec,
				productId: res.data.productId,
				productName: res.data.productName,
				purchasePrice: res.data.purchasePrice,
				regionCode: res.data.regionCode,
				supplierId: res.data.supplierId,
				typeName: res.data.typeName,
				unit: res.data.unit,
				remark: res.data.remark
			}
			getProductDetail(info.value?.productId)
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// form表单数据
	const formData = ref({
		moreSpec: 0,
		productId: '',
		productName: '',
		purchasePrice: '',
		regionCode: '',
		supplierId: '',
		typeName: '',
		unit: '',
		remark: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		typeName: {
			rules: [{ required: true, errorMessage: '请选择商品类别' }]
		},
		unit: {
			rules: [{ required: true, errorMessage: '请选择单位' }]
		},
		supplierId: {
			rules: [{ required: true, errorMessage: '请选择供应商' }]
		},
		regionCode: {
			rules: [{ required: true, errorMessage: '请选择区域' }]
		},
		productName: {
			rules: [{ required: true, errorMessage: '请选择商品' }]
		},
		purchasePrice: {
			rules: [{ required: true, errorMessage: '请输入采购价' }]
		}
	})
	
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const params = { ...formRes }
			if (id.value) {
				params.id = id.value
			}
			isSubmit.value = true
			editSupplierProduct(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				if (parseFloat(params.purchasePrice) == parseFloat(productInfo.value.purchasePrice)) {
					clear()
					uni.$emit('refreshList');  // 触发刷新事件
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.showModal({
						content: `商品信息采购价${productInfo.value.purchasePrice}与供应商商品采购价${params.purchasePrice}不一致，是否前往修改？`,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: `/pages/product/productEdit?id=${params.productId}`
								})
							}
							if (res.cancel) {
								clear()
								uni.$emit('refreshList');  // 触发刷新事件
								uni.navigateBack({
									delta: 1
								})
							}
						}
					})
				}
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			moreSpec: 0,
			productId: '',
			productName: '',
			purchasePrice: '',
			regionCode: '',
			supplierId: '',
			typeName: '',
			unit: '',
			remark: ''
		}
	}
</script>

<style scoped lang="scss">
	.operate {
		margin-left: auto;
	}
</style>
